/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package PaqueteServlet;

import cl.tienda.modelo.Carrito;
import cl.tienda.modelo.Producto;
import cl.tienda.modelo.Usuario;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Carlos
 */
public class ServletCAgrCarrito3 extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet ServletCAgrCarrito3</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet ServletCAgrCarrito3 at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession sesion = request.getSession();
        Vector<Carrito> carritoCompra = null;
        Vector<Producto> productos = (Vector<Producto>) sesion.getAttribute("productos");
        Usuario usuario = (Usuario) sesion.getAttribute("usuarioInicio");
        //Si se creo la sesion con el atributo de carrito
        if (sesion.getAttribute("Carrito") != null) {
            //Si existe una sesion con el atributo carrito, se obtiene los datos de esa sesion
            carritoCompra = (Vector<Carrito>) sesion.getAttribute("carrito");
        } else {
            //Si no existe esa sesion se crea el carrito de compras
            carritoCompra = new Vector<Carrito>();
        }

        //obtenemos los valores de las cajas de texto
        int indice = Integer.parseInt(request.getParameter("txtIndice").trim());
        int cantidad = Integer.parseInt(request.getParameter("txtCantidad").trim());
        float subTotal = cantidad * productos.get(indice).getPrecio();
        //creo el elemento carrito
        Carrito car = new Carrito();
        car.setCodigo(indice);
        car.setProducto(productos.get(indice));
        car.setCantidadPedida(cantidad);
        car.setSubTotal(subTotal);
        //agrego el carrito a mi vector
        carritoCompra.add(car);
        sesion.setAttribute("carrito", carritoCompra);
        PrintWriter out = response.getWriter();
        mostrarPagina(out, carritoCompra);
        out.close();
    }

    public void mostrarPagina(PrintWriter out, Vector<Carrito> carritoCompras) {
        //Vamos a mostrar la lista de productos del vector de Productos 
            for (int i = 0; i < carritoCompras.size(); i++) {
                if (i % 2 == 0) {
                    out.println("<tr bgcolor=\"#FFFFFF\">");
                    out.println("<td>" + carritoCompras.get(i).getProducto().getNombreProducto() + "</td>");
                    out.println("<td align=\"right\" valign=\"top\">" + carritoCompras.get(i).getCantidadPedida()+ "</td>");
                    out.println("<td align=\"right\" valign=\"top\">" + carritoCompras.get(i).getSubTotal()+ "</td>");
                    out.println("</tr>");
                } else {
                    out.println("<tr>");
                    out.println("<td>" + carritoCompras.get(i).getProducto().getNombreProducto() + "</td>");
                    out.println("<td align=\"right\" valign=\"top\">" + carritoCompras.get(i).getCantidadPedida()+ "</td>");
                    out.println("<td align=\"right\" valign=\"top\">" + carritoCompras.get(i).getSubTotal()+ "</td>");
                    out.println("</tr>");
                }
            }

            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet ServletCConProd</title>");
            out.println("</head>");
            out.println("<body>");
            
            out.println("</body>");
            out.println("</html>");
        
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
